package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.MarketRole;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.service.admin.AdminAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Bowen Deng
 * @since 2022/06/28 23:37
 */
@Service
public class AdminAuthServiceImpl implements AdminAuthService {

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    /**
     *  根据roleIds查询他所拥有的权限
     * @param roleIds
     * @return java.util.List<java.lang.String>
     * @author Bowen Deng
     * @since 2022/06/28 11:37 下午
     */
    @Override
    public List<String> getPermissionsByAdminId(Integer[] roleIds) {
        ArrayList<String> permissionList = new ArrayList<>();
        for (Integer roleId : roleIds) {
            List<String> permissions = marketRoleMapper.selectPermissionsByRoleId(roleId);
            permissionList.addAll(permissions);
        }
        if(permissionList.contains("*")){
            return Arrays.asList("*");
        }
        List<String> allPermissions = permissionList.stream()
                .distinct()
                .collect(Collectors.toList());
        return allPermissions;
    }

    /**
     *  根据roleIds查询他的角色
     * @param roleIds
     * @return java.util.List<java.lang.String>
     * @author Bowen Deng
     * @since 2022/06/28 11:37 下午
     */
    @Override
    public List<String> getRolesByAdminId(Integer[] roleIds) {
        ArrayList<String> roleList = new ArrayList<>();
        for (Integer roleId : roleIds) {
            MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(roleId);
            roleList.add(marketRole.getName());
        }
        return roleList;
    }

    @Override
    public List<String> getPermissionsApi(Integer[] roleIds) {
        List<String> permissions = getPermissionsByAdminId(roleIds);
        if (permissions.contains("*")){
            return permissions;
        }
        ArrayList<String> apis = new ArrayList<>();
        for (String permission : permissions) {
            String api = marketRoleMapper.selectAPIByPermission(permission);
            apis.add(api);
        }
        return apis;
    }
}
